package com.ml.loan.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.google.common.collect.Lists;
import com.ml.loan.common.constants.SysConstant;
import com.ml.loan.common.model.JsonResult;
import com.ml.loan.common.model.PageResult;
import com.ml.loan.common.redis.RedisService;
import com.ml.loan.common.redis.keys.SysConfigKey;
import com.ml.loan.common.utils.Convert;
import com.ml.loan.common.utils.StringUtils;
import com.ml.loan.sys.dao.SysConfigMapper;
import com.ml.loan.sys.model.SysConfig;
import com.ml.loan.sys.service.SysConfigService;
import com.ml.loan.sys.vo.AppSwitchConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author milian
 * @since 2020-02-11
 */
@Slf4j
@Service
public class SysConfigServiceImpl extends ServiceImpl<SysConfigMapper, SysConfig> implements SysConfigService {

    @Autowired
    private RedisService redisService;

    @Override
    public PageResult<SysConfig> list(Integer page, Integer limit, String configName) {
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(configName)) {
            wrapper.and(w -> w.like(SysConfig::getTitle, configName).or().like(SysConfig::getConfKey, configName).or().like(SysConfig::getConfValue, configName));
        }
        wrapper.orderByDesc(SysConfig::getCreateTime);
        IPage<SysConfig> iPage = page(new Page<>(Convert.toInt(page, 1), Convert.toInt(limit, 20)), wrapper);
        return new PageResult<>(iPage.getRecords(), iPage.getTotal());
    }

    @Override
    public boolean checkConfigExists(String confKey, Integer id) {
        LambdaQueryWrapper<SysConfig> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysConfig::getConfKey, confKey);
        if (id != null) {
            lambdaQueryWrapper.ne(SysConfig::getId, id);
        }
        return SqlHelper.retBool(count(lambdaQueryWrapper));
    }

    @Override
    public boolean syncConfig(Integer id) {
        return false;
    }

    @Override
    public SysConfig getSysConfig(String key) {
        String redisKey = key;
        SysConfig config = redisService.get(SysConfigKey.config, key, SysConfig.class);
        if (config == null) {
            config = baseMapper.selectOne(new LambdaQueryWrapper<SysConfig>().eq(SysConfig::getConfKey, key));
            if (config != null) {
                redisService.set(SysConfigKey.config, redisKey, config);
            }
        }
        return config;
    }

    @Override
    public List<SysConfig> getSysConfigs(String... keys) {
        if (keys == null || keys.length == 0) {
            return Lists.newArrayList();
        }
        List<SysConfig> list = new ArrayList<>();
        for (int i = 0; i < keys.length; i++) {
            SysConfig config = this.getSysConfig(keys[i]);
            if (config != null) {
                list.add(config);
            }
        }
        return list;
    }


    @Override
    public <T> T getConfigObj(String key, Class<T> clazz) {
        SysConfig config = getSysConfig(key);
        if (config != null && StringUtils.isNotBlank(config.getConfValue()) && clazz != null) {
            try {
                return JSON.parseObject(config.getConfValue(), clazz);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取配置对象异常，key:{}, className:{}", key, clazz.getName());
            }
        }
        return null;
    }


    @Override
    public <T> List<T> getConfigList(String key, Class<T> clazz) {
        SysConfig config = getSysConfig(key);
        if (config != null && StringUtils.isNotBlank(config.getConfValue()) && clazz != null) {
            try {
                return JSON.parseArray(config.getConfValue(), clazz);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取配置列表对象异常 key:{}, className:{}", key, clazz.getName());
            }
        }
        return null;
    }

    @Override
    public String getValueByKey(String key) {
        SysConfig config = getSysConfig(key);
        if (config != null) {
            return config.getConfValue();
        }
        return null;
    }

    @Override
    public JsonResult saveSwitchConfig(AppSwitchConfig switchConfig) {
        if (switchConfig == null || StringUtils.isBlank(switchConfig.getAppId())) {
            return JsonResult.error();
        }
        SysConfig sysConfig = getSysConfig(SysConstant.CONFIG_KEY.APP_SWITCH);
        if (sysConfig == null) {
            //新增APP配置
            sysConfig = SysConfig.builder().title("应用开关").confKey(SysConstant.CONFIG_KEY.APP_SWITCH)
                    .confValue(JSON.toJSONString(switchConfig)).build();
            if (save(sysConfig)) {
                return JsonResult.ok();
            }
        } else {
            //更新app配置
            sysConfig.setConfValue(JSON.toJSONString(switchConfig));
            if (updateById(sysConfig)) {
                return JsonResult.ok();
            }
        }
        return JsonResult.error();
    }
}
